package com.foreveross.bsl.util;

import android.content.Context;
import android.os.Environment;
import org.apache.http.util.EncodingUtils;

import java.io.*;

/**
 * 文件操作类
 *
 * @author Administrator tan
 */
public class FileCopeTool {
    /**
     *
     */
    private Context c;

    public FileCopeTool(Context c) {
        this.c = c;
    }

    /**
     * 读取内存卡某路径的文件
     *
     * @param path
     * @param name
     *
     * @return
     */
    public String readerFile(String path, String name) {
        String result = null;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File s = new File(path + "/" + name);
            try {
                FileInputStream in = new FileInputStream(s);
                // 获取文件的字节数
                int lenght = in.available();
                // 创建byte数组
                byte[] buffer = new byte[lenght];
                // 将文件中的数据读到byte数组中
                in.read(buffer);
                result = EncodingUtils.getString(buffer, "UTF-8");

            } catch(Exception e) {
            }
        }
        return result;
    }

    /**
     * 写文件。
     *
     * @param fileName
     * @param path
     * @param json
     *
     * @return
     */
    public boolean writeToJsonFile(String fileName, String path, String json) {
        Boolean flag = false;
        // 获取sd卡目录
        File file = null;
        OutputStream output = null;
        try {
            file = new File(path);
            if(!file.exists()) {
                file.mkdirs(); // 创建文件夹
            }
            file = new File(path + fileName + ".json");
            output = new FileOutputStream(file);
            output.write(json.getBytes());
            output.flush();
            flag = true;
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 判断SD里某路径的文件是否存在。
     *
     * @param path
     *
     * @return
     */
    public boolean isfileExist(String path, String name) {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File s = new File(path + "/" + name);
            if(s.exists()) {
                return true;
            } else {
                return false;
            }

        }
        return false;

    }

    /**
     * 删除SD卡某路径下的某个文件
     *
     * @param path
     */
    public void deleteFile(String path) {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File s = new File(path);
            s.delete();

        }
    }

    /**
     * 删除整个文件夹
     *
     * @param path
     */
    public static void deleteFolder(String path) {
        File f = new File(path);
        if(f.exists()) {
            // System.out.println("存在该文件夹");
            // 在判断它是不是一个目录
            if(f.isDirectory()) {
                // System.out.println("该文件夹是一个目录");
                // 列出该文件夹下的所有内容
                String[] fileList = f.list();
                if(fileList == null) {
                    return;
                }
                for(int i = 0; i < fileList.length; i++) {
                    // 对每个文件名进行判断
                    // 如果是文件夹 那么就循环deleteFolder
                    // 如果不是，直接删除文件
                    String name = path + File.separator + fileList[i];
                    File ff = new File(name);
                    if(ff.isDirectory()) {
                        deleteFolder(name);
                    } else {
                        ff.delete();
                    }
                }
                // 最后删除文件夹
                f.delete();

            } else {
                System.out.println("该文件夹不是一个目录");
            }
        } else {
            System.out.println("不存在该文件夹");
        }
    }

    /**
     * 从assets 文件夹中获取文件并读取数据
     *
     * @param fileName
     *
     * @return
     */
    public String getFromAssets(String fileName) {
        String result = "";
        try {
            InputStream in = c.getResources().getAssets().open(fileName);
            // 获取文件的字节数
            int lenght = in.available();
            // 创建byte数组
            byte[] buffer = new byte[lenght];
            // 将文件中的数据读到byte数组中
            in.read(buffer);
            result = EncodingUtils.getString(buffer, "ENCODING");
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    // 判断SDCard是否存在
    private static boolean isHaveSDCard() {
        String status = Environment.getExternalStorageState();
        if(status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 在内存卡新建一个文件夹
     *
     * @param path
     */
    public void createFile(String path) {
        String s = Environment.getExternalStorageDirectory().getPath();
        if(isHaveSDCard()) {
            System.out.println("path===" + s);
            File f = new File(s + "/" + path);
            if(!f.exists()) {
                System.out.println("文件夹不存在");
                f.mkdirs();
            }
        }
    }

    /**
     * 单个文件复制,dir的格式如“/sdcard/js/”+filePath
     *
     * @param filePath
     * @param dir
     * @param fileName
     *
     * @throws java.io.IOException
     */
    public void copyOneFileToSDCard(String filePath, String dir, String fileName) throws IOException {
        InputStream is = c.getAssets().open(filePath);
        BufferedInputStream inBuff = null;
        inBuff = new BufferedInputStream(is);

        byte[] buffer = new byte[1024];
        if(isHaveSDCard()) {
            File f = new File(dir);
            if(!f.exists()) {
                f.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(dir + fileName);
            int len = inBuff.read(buffer);
            while(len > 0) {
                fos.write(buffer, 0, len);
                len = inBuff.read(buffer);
            }
            fos.close();
            inBuff.close();

        }
    }

    /**
     * 复制Assets 里的整个文件夹到SD卡里
     *
     * @param assetDir
     * @param dir
     */
    public void CopyAssets(String assetDir, String dir) {
        String[] files;
        try {
            // 获得Assets一共有几多文件
            files = c.getResources().getAssets().list(assetDir);
        } catch(IOException e1) {
            return;
        }
        File mWorkingPath = new File(dir);
        // 如果文件路径不存在
        if(!mWorkingPath.exists()) {
            // 创建文件夹
            if(!mWorkingPath.mkdirs()) {
                // 文件夹创建不成功时调用
            }
        }

        for(int i = 0; i < files.length; i++) {
            try {
                // 获得每个文件的名字
                String fileName = files[i];
                // 根据路径判断是文件夹还是文件
                if(!fileName.contains(".")) {
                    if(0 == assetDir.length()) {
                        CopyAssets(fileName, dir + fileName + "/");
                    } else {
                        CopyAssets(assetDir + "/" + fileName, dir + "/" + fileName + "/");
                    }
                    continue;
                }
                File outFile = new File(mWorkingPath, fileName);
                if(outFile.exists()) {
                    outFile.delete();
                }
                InputStream in = null;
                if(0 != assetDir.length()) {
                    in = c.getAssets().open(assetDir + "/" + fileName);
                } else {
                    in = c.getAssets().open(fileName);
                }
                OutputStream out = new FileOutputStream(outFile);

                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();
            } catch(FileNotFoundException e) {
                e.printStackTrace();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 复制Assets 里的整个文件夹到SD卡里
     *
     * @param assetDir
     * @param dir
     */

    public boolean CopyAssetsFile(String assetFile, String sdFile) {
        try {
            File outFile = new File(sdFile);
            InputStream in = null;
            in = c.getAssets().open(assetFile);
            OutputStream out = new FileOutputStream(outFile);
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();
            return true;
        } catch(FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch(IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    public String[] getAssectFilePath(String identifier) {
        String[] files = null;
        try {
            files = c.getResources().getAssets().list("image/snapshot/" + identifier);
        } catch(IOException e) {
            e.printStackTrace();
        }
        return files;
    }
}
